package cn.schoolwow.quickserver;

import cn.schoolwow.quickserver.domain.ServerConfigMeta;
import cn.schoolwow.quickserver.server.HttpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class QuickServer {
    private Logger logger = LoggerFactory.getLogger(QuickServer.class);
    private ServerConfigMeta serverConfigMeta = new ServerConfigMeta();

    /**
     * 新建QuickServer实例
     */
    public static QuickServer newInstance() {
        return new QuickServer();
    }

    /**
     * 指定端口
     *
     * @param port 端口,为0表示使用系统分配端口
     */
    public QuickServer port(int port) {
        serverConfigMeta.port = port;
        return this;
    }

    /**
     * 扫描指定包
     *
     * @param packageName 包名
     */
    public QuickServer scan(String packageName) {
        serverConfigMeta.applicationContext.scan(packageName);
        return this;
    }

    /**
     * 注册指定类
     *
     * @param componentClass 容器类
     */
    public QuickServer register(Class componentClass) {
        serverConfigMeta.applicationContext.register(componentClass);
        return this;
    }

    /**
     * 指定静态路径前缀
     *
     * @param staticResourcePathPrefix 静态路径前缀
     */
    public QuickServer staticResourcePathPrefix(String staticResourcePathPrefix) {
        logger.info("[指定静态路径前缀]{}",staticResourcePathPrefix);
        if(!staticResourcePathPrefix.startsWith("/")){
            staticResourcePathPrefix = "/" + staticResourcePathPrefix;
        }
        serverConfigMeta.staticResourcePathPrefix = staticResourcePathPrefix;
        return this;
    }

    /**
     * 指定静态路径
     *
     * @param staticResourcePath 静态路径
     */
    public QuickServer staticResourcePath(String staticResourcePath) {
        logger.info("[指定静态路径]{}",staticResourcePath);
        serverConfigMeta.staticResourcePathMap.put(staticResourcePath,"");
        return this;
    }

    /**
     * 指定静态路径
     *
     * @param staticResourcePath 静态路径
     */
    public QuickServer staticResourcePath(String staticResourcePath, String urlPrefix) {
        logger.info("[指定静态路径]路径:{},url前缀:{}",staticResourcePath,urlPrefix);
        serverConfigMeta.staticResourcePathMap.put(staticResourcePath,urlPrefix);
        return this;
    }

    /**
     * 是否开启keepAlive特性
     *
     * @param keepAlive 是否开启keepAlive特性
     */
    public QuickServer keepAlive(boolean keepAlive) {
        serverConfigMeta.keepAlive = keepAlive;
        return this;
    }

    /**
     * 指定keepAlive超时时间(毫秒)
     *
     * @param keepAliveTimeout keepAlive超时时间
     */
    public QuickServer keepAliveTimeout(int keepAliveTimeout) {
        serverConfigMeta.keepAliveTimeout = keepAliveTimeout;
        return this;
    }

    public void start() throws IOException {
        HttpServer httpServer = new HttpServer(serverConfigMeta);
        httpServer.start();
    }
}
